import re
import time
import uuid
from django.test import TestCase
import pandas as pd
from openpyxl import load_workbook
from .yida_config import YidaClient
import unittest

admin_user_id = "6821270455650770"
yida_client = YidaClient()

class YidaTest(TestCase):
    def setUp(self) -> None:
        return super().setUp()
    def test_script(self):
        yida_client = YidaClient()
        '''导入合同模版'''
        df = pd.read_excel(r'/Users/xusijiao/Desktop/xiaming_py/reportservice/yida_app_service/zhongcheng/resource/合同信息_数据模板(2).xlsx')
        print("列名：", df.columns)
        # 初始化列表以存储字典
        import_data_list = []
        def convert_to_timestamp(date):
            if pd.isna(date) or isinstance(date, str) and date.strip() == '':  # 检查日期是否为空或仅包含空格
                return None
            return int(time.mktime(pd.to_datetime(date).timetuple()) * 1000)

        def split_contract_number(contract_number):
            # 更新正则表达式以匹配包含中文字符的前缀部分
            match = re.match(r"([^\d]+)(\d{4})(\d{3})", contract_number)
            if match:
                ht_part = match.group(1)  # 提取包含中文的前缀部分
                year_part = match.group(2)
                serial_number_part = int(match.group(3))  # 转换为整数类型
                return ht_part, year_part, serial_number_part
            return None
        
        def is_timestamp_before_now(timestamp):
            if timestamp is None:  # 检查时间戳是否为 None
                return False
            current_timestamp = int(time.time() * 1000)  # 获取当前系统时间的时间戳（毫秒）
            return timestamp < current_timestamp  # 如果时间戳在当前系统时间之前，返回 True

        # 遍历每一行，提取对应列的数据并转换日期
        for index, row in df.iterrows():
            # if index <= 262:
            #     continue
            # if row['合同编号'] == "(N)HJHT2024003":
            #     print(index)
            # continue
            form_data = {}
            if str(row['项目名称']).strip():
                form_data_list = yida_client.get_form_data_by_search_field('FORM-CCDDFACAAF2B42CA9E471E9C9B13D8A84XCS',admin_user_id,
                [
                    {
                        "key": "textField_lvhea611",
                        "value": row['项目名称'],
                        "type": "TEXT",
                        "operator": "eq",
                        "componentName": "TextField"
                    }
                ])
                form_data:dict = form_data_list[0].form_data #项目登记信息

            try:
                contract_total_price = float(row['合同总价'])
                non_numeric_text = None
            except ValueError:
                contract_total_price = 0
                non_numeric_text = row['合同总价']

            result = split_contract_number(row['合同编号'])

            if result is None:
                contract_number_code, year, water_number = None, None, 0
            else:
                contract_number_code, year, water_number = result

            def is_zhht(contract_number_code):
                if contract_number_code and 'ZHHT' in contract_number_code:
                    return '是' 
                elif contract_number_code and 'ZHHT' not in contract_number_code:
                    return '否' 
                else:
                    return None

            data_dict = {
                'textField_lx2wsefr': row['合同编号'],
                'dateField_lvhud9rh': convert_to_timestamp(row['登记日期']),
                'associationFormField_lxmuhyzd':[
                    {
                        "appType": 'APP_WKZFN067VOERIQ13N5RI', 
                        "formType": 'receipt',
                        "formUuid": 'FORM-CCDDFACAAF2B42CA9E471E9C9B13D8A84XCS',
                        "instanceId": form_data_list[0].form_instance_id,
                        "title": form_data['textField_lvhea611'],
                        "subTitle": form_data["serialNumberField_lvkohqt7"],
                    }
                ] if form_data else None,
                'textField_lzt601ce':row['项目名称'],
                'textField_lvhud9rv': row['合同内容'],
                'numberField_lvhud9s1': contract_total_price, #合同总价
                'textField_lxmushym': row['业务员'],
                'dateField_lzrr88t6': convert_to_timestamp(row['签订日期']),
                'dateField_lzrr88t7': convert_to_timestamp(row['盖章日期']),
                'dateField_lzrrdp91': convert_to_timestamp(row['归档日期']),
                'textField_lzrrdp9h': row['项目负责人'],
                'textField_lzrrdp9i': row['所属房产集团'],
                'selectField_lzs0w59w': row['*项目属地'],
                'textField_lzt86amh':str(uuid.uuid4()),
                'textareaField_lvhud9sb':non_numeric_text,
                'textField_lzunxdev':form_data['serialNumberField_lvkohqt7'] if form_data else None,
                'textField_lzt601cd':contract_number_code,#合同编号代码
                'numberField_lvvsudxa':water_number,
                'selectField_lzs0w59w':form_data['selectField_lzs3qirc'] if form_data else None,#项目属地
                'textField_lzs0w5b3':form_data['textField_lzs3qird'] if form_data else None,
                'radioField_lzs0w5ba':is_zhht(contract_number_code),
                'textField_lzs0w5b9':form_data['textField_lzw538la'] if form_data else None,#项目地址
                'textField_lzs0w59x':form_data.get('textField_lvhea612','')if form_data else None,
                'selectField_lzrrdp94':'已归档' if is_timestamp_before_now(convert_to_timestamp(row['归档日期'])) else '未归档',
                'textField_m0364vxn':row['建设单位'],
                'textField_m037p8qt':row['检测方法'],
                'textField_m037p8qw':row['检测单价'],
                'textareaField_m037p8r6':row['付款方式'],
                'textField_m037p8qn':row['施工单位']
            }
            # import_data_list.append(json.dumps(data_dict))
            print(f"合同编号:{data_dict['textField_lx2wsefr']}")
            print(f"合同编号代码:{data_dict['textField_lzt601cd']}")
            print(f"第{index+1}条数据处理完成")
            yida_client.create_process_instance("FORM-28B03077002B4274B2F758E9EEC4C748O2FN",admin_user_id,data_dict,"TPROC--AD866891K8NNHDWQBZTUM889SICG3UR9XQRZLF")